package com.kly.user.serviceImpl.traffic.homepage;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.service.MemberService;
import com.kly.user.db.dao.CustomersUserDao;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.CustomersUserEntity;
import com.kly.user.db.entity.IssueUserPoolEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.db.entity.UserPreHomepageEntity;
import com.kly.user.dto.TrafficSourceDto;
import com.kly.user.dto.vo.TrafficSourceReq;
import com.kly.user.enums.*;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MebooHomepage extends HomepageBase {


    @PostConstruct
    public void init() {
        HomepageTrafficHandler.homepageBaseMap.put(AppEnum.MEBOO.getUserAppFlag(), this);
        HomepageTrafficHandler.homepageBaseMap.put(AppEnum.MEBOO_IOS.getUserAppFlag(), this);
    }

    @Override
    public List<UserEntity> queryUsers(UserEntity currentUser, Integer recordNum, Integer lookingFor) {

        Response<Boolean> inWhiteList = whiteListService.in(currentUser.getAppCode(), currentUser.getUserCode(), currentUser.getMobile(), currentUser.getEmail());
        Integer filterUserType = inWhiteList.getData() ? UserType.MODEL.getType() : null;

        String userCode = currentUser.getUserCode();
        logger.info("==queryUsers 开始 ==,当前用户:{}", userCode);
        List<UserEntity> userEntities = new ArrayList<>();
        List<String> userCodeList = new ArrayList<>();

        if (userCode.equals("1762036137478590464") || userCode.equals("1731596961893679104")) {
            userCodeList = userDao.queryIOSRecommendUsers(recordNum);
        } else {
            logger.info("==queryUsers 当前采用的策略版本 ==,version:{}", homepageNewPolicyVersion);
            Response<Boolean> response = memberService.ifMember(userCode);
            if (response.isSuccess()) {
                Boolean member = response.getData();
                List<Integer> poolNums = new ArrayList<>();
                if (member) {
                    poolNums.add(2);
                    poolNums.add(3);
                    poolNums.add(4);
                } else {
                    poolNums.add(1);
                }

                if (inWhiteList.getData()) {
                    poolNums.add(3);
                }
                logger.info("===homeModelV3, userCode:{}, 是否会员：{}，池子：{}", userCode, member, JSONObject.toJSONString(poolNums));
                CustomersUserEntity customersUserEntity = customersUserDao.getCustomer(userCode);
                List<IssueUserPoolEntity> userCodeEntityList;
                if (customersUserEntity == null) {
                    logger.error("===homeModelV3, 找不到当前用户的客户信息,先走V2版本，userCode:{}, 是否会员：{}，池子：{}", userCode, member, JSONObject.toJSONString(poolNums));
                    userCodeEntityList = userDao.queryIssueUserPoolV2(userCode, lookingFor, poolNums, recordNum, filterUserType != null ? filterUserType : 0);
                } else {
                    logger.error("===homeModelV3, 找到当前用户的客户信息，走客户隔离逻辑，userCode:{}, 是否会员：{}，池子：{}", userCode, member, JSONObject.toJSONString(poolNums));
                    userCodeEntityList = userDao.queryIssueUserPoolV3(userCode, customersUserEntity.getCustomerCode(), lookingFor, poolNums, recordNum, filterUserType != null ? filterUserType : 0);
                }

                if (CollectionUtils.isNotEmpty(userCodeEntityList)) {
                    userCodeList = userCodeEntityList.stream().map(IssueUserPoolEntity::getUserCode).collect(Collectors.toList());
                }

                logger.info("===homeModelV2, userCode:{}, 是否会员：{}，池子：{}, 返回参数:{}", userCode, member, JSONObject.toJSONString(poolNums), JSONObject.toJSONString(userCodeEntityList));


            }
        }

        updateConnectCount(userEntities, userCodeList);
        sendPush(userCode, userEntities, userCodeList);
        return userEntities;
    }

    private Integer getFilterUsertypeForRecommend(UserEntity currentUser) {
        TrafficSourceReq req = TrafficSourceReq.builder()
                .userCode(currentUser.getUserCode())
                .appCode(currentUser.getAppCode())
                .mobile(currentUser.getMobile())
                .email(currentUser.getEmail())
                .build();
        Response<TrafficSourceDto> resp = userTrafficSourceService.getTrafficSource(req);
        if (!resp.isSuccess() || resp.getData() == null) {
            return null;
        }

        if (resp.getData().getWhiteFlag() == 1) {
            return UserType.MODEL.getType();
        }

        return null;
    }


}
